public class Solution {
    /*
     * 二叉树的层序遍历
     * BFS
     * */
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> alist = new ArrayList<>();
            while (size > 0) {
                TreeNode node = queue.poll();
                alist.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
            list.add(alist);
        }
        return list;
    }

    /*
     * 二叉树的层序遍历
     *
     * 求二叉树的最大深度，知道list的大小，list中每一层有一个alist，进行深度优先搜索，对alist赋值
     *
     * */
    public int Treehigh(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHigh = Treehigh(root.left);
        int rightHigh = Treehigh(root.right);
        return (leftHigh > rightHigh ? leftHigh : rightHigh) + 1;
    }

    public void leOrder(TreeNode root, List<List<Integer>> list, int high) {
        if (root == null) {
            return;
        }
        list.get(high).add(root.val);
        leOrder(root.left, list, high + 1);
        leOrder(root.right, list, high + 1);
    }

    public List<List<Integer>> levelOrder2(TreeNode root) {
        int high = Treehigh(root);
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < high; i++) {
            list.add(new ArrayList<>());
        }
        leOrder(root, list, 0);
        return list;
    }

    /*
     * DFS
     * 不求二叉树的最大深度
     * */
    public void leOrder3(TreeNode root, List<List<Integer>> list, int high) {
        if (root == null) {
            return;
        }
        if (list.size() < high + 1) {
            list.add(new ArrayList<>());
        }
        list.get(high).add(root.val);
        leOrder3(root.left, list, high + 1);
        leOrder3(root.right, list, high + 1);
    }

    public List<List<Integer>> levelOrder3(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        leOrder3(root, list, 0);
        return list;
    }
}